<template>
  <div id="create">
    <div class="main-box">
      <div class="form">
        <div class="form-title">
          <i class="iconfont icon-md-hammer"></i>铸造NFT艺术品
        </div>
        <div class="art-name">
          <div class="tip tip-need">艺术品名称</div>
          <el-input
            placeholder="请输入艺术品名称"
            suffix-icon="el-icon-edit"
            v-model="formParams.name"
            clearable
            maxlength="30"
            show-word-limit
          >
          </el-input>
        </div>
        <!-- 艺术品形式 -->
        <div class="choose-type">
          <div class="tip tip-need">选择艺术品的类型（图片，视频，文本）</div>
          <el-select v-model="formParams.type" placeholder="请选择艺术品类型">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </div>
        <!-- 上传文件 -->
        <div class="upload">
          <div v-if="formParams.type == 'img'">
            <el-upload
              class="upload-img"
              action=""
              list-type="picture-card"
              accept=".jpeg,.png,.jpg,.gif,.svg"
              :on-remove="onRemove"
              :on-change="onUploadChange"
              :auto-upload="false"
              :limit="1"
            >
              <i class="el-icon-plus"></i>
              <div class="el-upload__tip" slot="tip">
                只能上传 jpg/png/gif/svg 文件，且不超过10M
              </div>
            </el-upload>
          </div>
        </div>
        <!-- 上传视频 -->
        <div class="upload">
          <div v-if="formParams.type == 'video'">
            <el-upload
              class="upload-img"
              action=""
              accept=".mp4"
              :on-remove="onRemoveVideo"
              :on-change="onUploadChangeVideo"
              :auto-upload="false"
              :limit="1"
            >
              <el-button icon="el-icon-plus" type="primary">上传</el-button>
              <div class="el-upload__tip" slot="tip">
                只能上传 mp4 文件，且不超过100M
              </div>
            </el-upload>
          </div>
        </div>
        <!-- 拍卖形式
        <div class="sale-type">
          <div class="tip">拍卖形式</div>
          <div class="hint">
            选择拍卖形式，定价交易为直接交易；拍卖则为竞价出售，需要设置起始价格
          </div>
          <div>
            <el-radio-group
              fill="#F38181"
              size="small"
              v-model="formParams.saleType"
            >
              <el-radio-button label="定价出售"></el-radio-button>
              <el-radio-button label="拍卖"></el-radio-button>
            </el-radio-group>
          </div>
        </div> -->
        <!-- 加入合集 -->
        <div class="add-to-collection">
          <div class="tip">加入合集</div>
          <!-- 创建合集按钮 -->
          <div class="select-collections">
            <div
              class="add-collection add-item"
              @click="$store.dispatch('showCreateCollection', true)"
            >
              <i class="icon-add iconfont"></i>
              <div>创建合集</div>
            </div>
            <div
              class="collection-item add-item"
              v-for="array in myArrays"
              :class="{ selected: array.id == formParams.selectedCol }"
              :key="array.id"
              @click="selectCollection(array.id)"
            >
              <div class="col-title">{{ array.title }}</div>
              <div class="col-cover">
                <img :src="array.logo | ipfsHash" alt="" />
              </div>
            </div>
          </div>
        </div>
        <!-- 拍卖价格 -->
        <!-- <div class="price">
          <template v-if="formParams.saleType == '拍卖'" class="tip"
            ><div class="price-tip tip-need">起始价：</div></template
          >
          <template v-else>
            <div class="price-tip tip-need">售价：</div>
          </template>
          <el-input
            class="price-input"
            v-model="formParams.price"
            placeholder="价格"
            type="number"
          ></el-input>
          <el-select
            style="width: 100px"
            v-model="formParams.unit"
            placeholder="请选择"
          >
            <el-option
              v-for="item in units"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </div> -->
        <!-- 设定作者佣金 -->
        <div class="commission-box">
          <div class="tip tip-need">设定作者佣金</div>
          <div class="hint">每笔交易都能给作者一定百分比的佣金</div>
          <el-input-number
            v-model="formParams.commission"
            :precision="2"
            :step="0.1"
            :max="5"
            :min="2"
          ></el-input-number>
          <span class="danwei">%</span>
        </div>
        <!-- 艺术品描述 -->
        <div class="art-desc">
          <div class="tip tip-need">艺术品描述</div>
          <div class="hint">描述上传艺术品的详细信息</div>
          <el-input
            type="textarea"
            class="desc-input"
            :rows="5"
            placeholder="请输入内容"
            v-model="formParams.desc"
          >
          </el-input>
        </div>
        <div class="create-btn" @click="submitUpload">提交创作</div>
      </div>
    </div>
    <!-- 创建合集弹窗 -->
    <CreateCollection />
  </div>
</template>

<script>
import CreateCollection from "./CreateCollection";
import { saveImageOnIpfs } from "@/utils/ipfsUtil";
import { mapState } from "vuex";
import { putShop } from "@/api";
export default {
  name: "Create",
  components: {
    CreateCollection,
  },
  data() {
    return {
      // 艺术品类型
      options: [
        { label: "图片（jpg, png, gif, svg)", value: "img" },
        { label: "视频 (mp4)", value: "video" },
      ],
      //   价格单位
      units: [
        { label: "ETH", value: "ETH" },
        { label: "Wei", value: "Wei" },
      ],
      formParams: {
        name: "",
        type: "",
        saleType: "定价出售",
        price: 0,
        unit: "Wei",
        desc: "",
        // 选中的合集
        selectedCol: -1,

        // 佣金
        commission: 2,
      },
      imgFile: null,
      videoFile: null,
    };
  },
  methods: {
    // 取消选取
    onRemove() {
      this.imgFile = null;
    },

    // 选取图片
    onUploadChange(file) {
      const isIMAGE =
        file.raw.type === "image/jpeg" ||
        file.raw.type === "image/png" ||
        file.raw.type === "image/jpg" ||
        file.raw.type === "image/gif" ||
        file.raw.type === "image/svg";
      const isLt10M = file.size / 1024 / 1024 < 10;

      if (!isIMAGE) {
        this.$message.error("只能上传jpg/png/gif/svg图片!");
        return false;
      }
      if (!isLt10M) {
        this.$message.error("上传文件大小不能超过 10MB!");
        return false;
      }

      this.imgFile = file.raw;
    },

    // 取消选取
    onRemoveVideo() {
      this.videoFile = null;
    },

    // 选取图片
    onUploadChangeVideo(file) {
      const isIMAGE = file.raw.type === "video/mp4";
      const isLt10M = file.size / 1024 / 1024 < 100;

      if (!isIMAGE) {
        this.$message.error("只能上传mp4文件");
        return false;
      }
      if (!isLt10M) {
        this.$message.error("上传文件大小不能超过 100MB!");
        return false;
      }

      this.videoFile = file.raw;
    },

    // 上传提交
    submitUpload() {
      // 校验
      let { name, type, desc, commission } = this.formParams;
      if (name.trim() == "" || desc.trim() == "" || type.trim() == "") {
        this.$message.warning("请完成信息填写");
        return;
      }
      if (
        (type == "img" && this.imgFile == null) ||
        (type == "video" && this.videoFile == null)
      ) {
        this.$message.error("未选择上传的艺术品");
        return;
      }
      if (type == "img") {
        type = "图片";
      } else if (type == "video") {
        type = "视频";
      }
      // 上传图片
      if (type == "图片") {
        let reader = new FileReader();
        // 缩略图
        let miniReader = new FileReader();
        let miniImg = new Image();
        let miniHash = "";
        let coverHash = "";
        // 选择的文件对象
        let file = this.imgFile;
        // 缩放图片需要的canvas
        let canvas = document.createElement("canvas");
        let context = canvas.getContext("2d");
        miniReader.readAsDataURL(this.imgFile);
        miniReader.onload = (e) => {
          miniImg.src = e.target.result;
        };
        miniImg.onload = function () {
          // 图片原始尺寸
          let originWidth = this.width;
          let originHeight = this.height;
          // 最大尺寸限制
          let maxWidth = 1000,
            maxHeight = 1000;
          // 目标尺寸
          let targetWidth = originWidth,
            targetHeight = originHeight;
          // 图片尺寸超过400x400的限制
          if (originWidth > maxWidth || originHeight > maxHeight) {
            if (originWidth / originHeight > maxWidth / maxHeight) {
              // 更宽，按照宽度限定尺寸
              targetWidth = maxWidth;
              targetHeight = Math.round(
                maxWidth * (originHeight / originWidth)
              );
            } else {
              targetHeight = maxHeight;
              targetWidth = Math.round(
                maxHeight * (originWidth / originHeight)
              );
            }
          }

          // canvas对图片进行缩放
          canvas.width = targetWidth;
          canvas.height = targetHeight;
          // 清除画布
          context.clearRect(0, 0, targetWidth, targetHeight);
          // 图片压缩
          context.drawImage(miniImg, 0, 0, targetWidth, targetHeight);
          canvas.toBlob(function (blob) {
            // 上传
            console.log(blob);
            let newMiniReader = new FileReader();
            newMiniReader.readAsArrayBuffer(blob);
            newMiniReader.onloadend = () => {
              // 上传到ipfs
              saveImageOnIpfs(newMiniReader).then((hash) => {
                // 上传请求
                miniHash = hash;
                reader.readAsArrayBuffer(file);
              });
            };
          }, file.type || "image/png");
        };
        reader.onloadend = () => {
          // 保存图片到ipfs，获取图片hash
          saveImageOnIpfs(reader).then((hash) => {
            // 上传请求
            let updataParams = {
              title: name,
              classify: type,
              shop_hash: hash,
              cover_hash: miniHash,
              info: desc,
              creator_address: this.$store.getters.user_address,
              commission: commission.toString(),
            };
            if (this.formParams.selectedCol != -1) {
              updataParams.array_id = this.formParams.selectedCol;
            }
            putShop(updataParams).then((result) => {
              if (result.flag) {
                this.$message.success(result.msg);
                this.$router.go(-1);
              } else {
                this.$message.error(result.msg);
              }
            });
          });
        };
      } else if (type == "视频") {
        // 上传视频
        let blob = new Blob([this.videoFile]), // 文件转化成二进制文件
          url = URL.createObjectURL(blob); //转化成url
        console.log(blob, url);
        let oVideo = document.createElement("video");
        oVideo.setAttribute("src", url);
        oVideo.setAttribute("controls", "controls");
        oVideo.currentTime = 1; // 设置当前视频为 第1s
        console.dir(oVideo);
        /*
            oVideo.addEventListener('canplay', function (event){
                let oCanvas = document.createElement('canvas');
                setTimeout( ()=>{
                    oCanvas.width = oVideo.videoWidth;
                    oCanvas.height = oVideo.videoHeight;
                    oCanvas.getContext("2d").drawImage(oVideo, 0, 0, oCanvas.width, oCanvas.height * 2);
                    console.log(oCanvas.toDataURL("image/png")); //第一帧图片url
                }, 1000 )
            });
*/
        oVideo.addEventListener("canplay", (event) => {
          let oCanvas = document.createElement("canvas");
          oCanvas.width = oVideo.videoWidth;
          oCanvas.height = oVideo.videoHeight;
          oCanvas
            .getContext("2d")
            .drawImage(oVideo, 0, 0, oCanvas.width, oCanvas.height);
          oCanvas.toBlob((blob) => {
            // 上传
            let reader = new FileReader();
            reader.readAsArrayBuffer(blob);
            reader.onloadend = async () => {
              // 上传封面到ipfs
              let coverHash = await saveImageOnIpfs(reader);
              let shopReader = new FileReader();
              shopReader.readAsArrayBuffer(this.videoFile);
              shopReader.onloadend = async () => {
                let shopHash = await saveImageOnIpfs(shopReader);
                // 上传请求
                let updataParams = {
                  title: name,
                  classify: type,
                  shop_hash: shopHash,
                  cover_hash: coverHash,
                  info: desc,
                  creator_address: this.$store.getters.user_address,
                  commission: commission.toString(),
                };
                if (this.formParams.selectedCol != -1) {
                  updataParams.array_id = this.formParams.selectedCol;
                }
                putShop(updataParams).then((result) => {
                  if (result.flag) {
                    this.$message.success(result.msg);
                    this.$router.go(-1);
                  } else {
                    this.$message.error(result.msg);
                  }
                });
              };
            };
          }, this.videoFile.type || "image/png");
        });
      }
    },

    // 选中合集
    selectCollection(id) {
      if (this.formParams.selectedCol == id) {
        this.formParams.selectedCol = -1;
      } else {
        this.formParams.selectedCol = id;
      }
    },
  },

  computed: {
    ...mapState({
      myArrays: (store) => store.create.myArrays,
    }),
  },

  mounted() {
    this.$store.dispatch("myArrays", {
      pageIndex: "1",
      pageSize: "1000",
    });
  },
};
</script>

<style lang='less'>
#create {
  margin: 0 auto;
  margin-top: 20px;
  margin-bottom: 100px;
  .main-box {
    max-width: 900px;
    min-width: 600px;
    padding: 0 20px;
    .form {
      .form-title {
        i {
          margin-right: 10px;
          color: var(--themeColor1);
          background: var(--themeColor2);
          padding: 5px;
          border-radius: 50%;
        }
        font-size: 22px;
        font-weight: bold;
      }
      .tip {
        font-size: 16px;
        margin-bottom: 5px;
      }
      .tip-need::before {
        content: "*";
        color: red;
        margin-right: 5px;
      }
      .hint {
        margin-bottom: 5px;
        font-size: 14px;
        color: #999;
      }
      .art-name {
        margin-top: 35px;
        max-width: 400px;
      }
      .choose-type {
        margin-top: 35px;
      }
      .upload {
        .upload-img {
          margin-top: 15px;
          .el-upload-list--picture-card .el-upload-list__item {
            width: auto !important;
          }
        }
      }
      .sale-type {
        margin-top: 35px;
        .el-radio-button__inner:hover {
          color: var(--themeColor1);
          opacity: 0.5;
          transition: 0.5s ease;
        }
        .is-active {
          .el-radio-button__inner:hover {
            color: #fff;
          }
        }
      }
      .add-to-collection {
        margin-top: 35px;
        .select-collections {
          display: flex;
          flex-wrap: wrap;
          .add-item {
            cursor: pointer;
            width: 100px;
            height: 100px;
            margin-right: 20px;
            border-radius: 10px;
            display: flex;
            justify-content: center;
            flex-direction: column;
            align-items: center;
            margin-bottom: 20px;
          }
          .add-item:hover {
            border-color: var(--themeColor1);
          }
          .add-collection {
            border: 1px dashed rgba(0, 0, 0, 0.3);
            color: #999;
            i {
              font-size: 18px;
            }
            div {
              margin-top: 10px;
              font-size: 12px;
            }
          }

          .collection-item {
            border: 1px solid rgba(0, 0, 0, 0.3);
            position: relative;
            i {
              font-size: 18px;
            }
            div {
              font-size: 12px;
            }
            .col-title {
              color: #fff;
            }
            .col-cover {
              position: absolute;
              top: -1px;
              left: -1px;
              right: -1px;
              bottom: -1px;
              z-index: -1;
              filter: brightness(0.6);
              img {
                border-radius: 10px;
                height: 100%;
                width: 100%;
                object-fit: cover;
              }
            }
          }
          .selected {
            border-color: var(--themeColor1) !important;
            border-width: 2px !important;
            .col-title {
              color: var(--themeColor1) !important;
            }
          }
        }
      }
      .price {
        margin-top: 35px;
        display: flex;
        align-items: center;
        .price-tip {
          white-space: nowrap;
        }
        .price-input {
          width: 180px;
        }
      }
      .art-desc {
        margin-top: 35px;
        .desc-input {
          max-width: 800px;
        }
      }
      .commission-box {
        margin-top: 35px;
        .danwei {
          margin-left: 10px;
        }
      }
      .create-btn {
        margin-top: 35px;
        cursor: pointer;
        display: inline-block;
        background: var(--themeColor1);
        font-size: 14px;
        color: #fff;
        padding: 10px 18px;
        border-radius: 40px;
      }
      .create-btn:hover {
        opacity: 0.5;
        transition: 0.5s ease;
      }
    }
  }
}
</style>